import router from "./index";
import store from "@/store";
import NProgress from "nprogress";
import "nprogress/nprogress.css";

NProgress.configure({
  showSpinner: false, // 禁用进度环
});

// 白名单
const whiteList = [];

router.beforeEach(async (to, from, next) => {
  NProgress.start();

  const token =
    process.env.NODE_ENV === "development"
      ? "token"
      : sessionStorage.getItem("token");

  if (token) {
    store.dispatch("user/setToken", token);
    // 已登录禁止跳转登录页
    if (to.path === "/login") {
      next({ path: "/" });
      NProgress.done();
    } else {
      const hasMenu = store.getters.menuList && store.getters.menuList.length;
      // 已获取用户菜单放行
      if (hasMenu) {
        if (to.redirectedFrom === "/") {
          NProgress.done();
          toFirstRoute(next);
        } else {
          next();
        }
      } else {
        try {
          // 获取用户菜单列表
          const menus = await store.dispatch("user/getMenuList");
          // 生成前端路由
          const accessRoutes = await store.dispatch(
            "permission/generateRoutes",
            menus
          );
          // 添加至用户路由列表
          accessRoutes.forEach((item) => {
            router.addRoute(item);
          });
          if (to.path === "/") {
            toFirstRoute(next);
          } else {
            next({ ...to, replace: true });
          }
        } catch (err) {
          // token失效或登录失败 跳转登录页面
          location.href = "";
          NProgress.done();
        }
      }
    }
  } else {
    // 未获取到token 白名单放行 或跳转登录
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      location.href = "https://www.baidu.com";
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});

function toFirstRoute(next) {
  const noHiddenRoutes = filterNoHiddenRoutes(store.getters.permission_routes);
  noHiddenRoutes.length
    ? next({ ...noHiddenRoutes[0], replace: true })
    : next("/401");
}

function filterNoHiddenRoutes(routes) {
  const res = [];
  routes.forEach((route) => {
    const tmp = { ...route };
    if (!tmp.hidden) {
      if (tmp.children) {
        tmp.children = filterNoHiddenRoutes(tmp.children);
      }
      res.push(tmp);
    }
  });
  return res;
}
